package com.gszkc.service.impl;

import com.gszkc.dto.GoodsSalesDTO;
import com.gszkc.entity.Orders;
import com.gszkc.mapper.OrderMapper;
import com.gszkc.mapper.UserMapper;
import com.gszkc.service.OrderService;
import com.gszkc.service.ReportService;
import com.gszkc.service.WorkspaceService;
import com.gszkc.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间内的营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //算出每天的时间并拼接字符串
        List<LocalDate> dateList = joinLocalDate(begin,end);

        List<Double> turnoverList = new ArrayList<>();
        //查询 订单是已完成的订单的金额并且在时间端内累加起来
        for (LocalDate date : dateList) {
            //先把时间完善成"一天内"
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select sun(amount) from orders where order_time > ? and order_time < ? and status = 5
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMay(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //算出每天的时间并拼接字符串
        List<LocalDate> dateList = joinLocalDate(begin,end);

        //select count(user) from user where create_time < end and create_time > begin
        List<Integer> newUserList = new ArrayList<>();
        //select count(user) from user where create_time < begin
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //先把时间完善成"一天内"
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //开始根据条件查询用户数量
            Map map = new HashMap();
            map.put("end",endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //算出每天的时间并拼接字符串
        List<LocalDate> dateList = joinLocalDate(begin,end);
        //总订单select count(id) from orders where orderTime > ? and orderTime < ?
        List<Integer> countOrderList = new ArrayList<>();
        //有效订单select count(id) from orders where orderTime > ? and orderTime < ? and status = 5
        List<Integer> validOrderList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime   = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",null);
            Integer countOrder = orderMapper.countByMap(map);
            countOrderList.add(countOrder);
            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.countByMap(map);
            validOrderList.add(validOrder);
        }

        Integer totalOrderCount = countOrderList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate =
                totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount ;


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(countOrderList,","))
                .validOrderCountList(StringUtils.join(validOrderList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MIN);
        List<GoodsSalesDTO> salesTop = orderMapper.getSalesTop(beginTime, endTime);
        List<String> nameList = salesTop.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> NumberList = salesTop.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(NumberList,","))
                .build();
    }

    private List<LocalDate> joinLocalDate(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 导出运营报表
     * @param response
     */
    public void exportData(HttpServletResponse response) {
        //1查询数据库，获取营业数据，30天最近数据。
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime Begin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime End = LocalDateTime.of(end, LocalTime.MAX);

        BusinessDataVO Data = workspaceService.getBusinessData(Begin, End);

        //2通过POI将数据写入Excel文件
        //先获取到模板，POI读取
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //获取Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充第2行数据
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间" + begin + "至" + end);
            //填充第4行数据
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(Data.getTurnover());
            row.getCell(4).setCellValue(Data.getOrderCompletionRate());
            row.getCell(6).setCellValue(Data.getNewUsers());
            //填充第5行数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(Data.getValidOrderCount());
            row.getCell(4).setCellValue(Data.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());

            }

            //3通过输出流将Excel文件下载到客户端游览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
